package com.sc.byahi.user.server;

import java.util.logging.Level;
import java.util.logging.Logger;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.Query;

public class ProfileIdGenerator {
	Logger logger = Logger.getLogger("com.sc.byahi.user.server.ProfileIdGenerator");
	public static void main(String[] args) {
		System.out.println(ProfileIdGenerator.generateProfileID("IN", 999999999l));
	}

	/**
	 * For referring while JVM is running.
	 */
	private Key profileIdKey;

	private static ProfileIdGenerator singleton = new ProfileIdGenerator();

	private ProfileIdGenerator() {
	}

	public static ProfileIdGenerator get(){
		return singleton;
	}
	
	public synchronized Long getNewProfileId() {
		logger.log(Level.INFO, "Creating new profile id.");
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		Entity p = null;
		if (profileIdKey == null) {// when method is called for the first time
			Query q = new Query("ProfileID");
			p = datastore.prepare(q).asSingleEntity();
			if (p == null) {// application just started, no profile in db yet
				p = new Entity("ProfileID");
				p.setProperty("lastProfileId", 0l);
				datastore.put(p);
			}
			profileIdKey = p.getKey();
		} else {
			try {
				p = datastore.get(profileIdKey);
			} catch (EntityNotFoundException e) {
				logger.log(Level.SEVERE, "Could not find ProfileID entity. It's bad.");
			}
		}
		Long lastProfileId = (Long) p.getProperty("lastProfileId");
		Long newProfileId = lastProfileId + 1;

		p.setProperty("lastProfileId", newProfileId);
		datastore.put(p);
		notifyAll();
		return newProfileId;
	}

	public static synchronized String generateProfileID(String countryCode, Long currentNumber) {
		String numberInString = currentNumber.toString();
		return countryCode + numberInString;
	}
}
